package gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import bd.ConsultasTableModel;
import bd.Resultado;
import bd.Servicios;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class VentanaMorosos extends javax.swing.JInternalFrame {
	private JLabel jnombre;
	private JPanel jPanel2;
	private Servicios serv;
	private JScrollPane jScrollPane;
	private JScrollPane jScrollPane1;
	private JButton cargarTabla;
	private JPanel informacion;
	private JPanel cartel;
	private JPanel tablaImpagos;
	private JTable cuotasImpagas;
	private JLabel infoP;
	private JPanel pnlAux;
	private JPanel jPanel3;
	private JPanel Clientes;
	private JTable tabla;
	private int cliente;
	private int prestamo;

	public VentanaMorosos() {
		super();
		initGUI();
		serv = Servicios.getServicios();
	}

	private void initGUI() {
		try {
			this.setPreferredSize(new java.awt.Dimension(741, 471));
			this.setBounds(0, 0, 741, 471);
			BorderLayout thisLayout = new BorderLayout();
			getContentPane().setLayout(thisLayout);
			this.setVisible(false);
			{
				jPanel2 = new JPanel();
				BorderLayout jPanel2Layout = new BorderLayout();
				getContentPane().add(jPanel2, BorderLayout.NORTH);
				jPanel2.setPreferredSize(new java.awt.Dimension(730, 62));
				jPanel2.setLayout(jPanel2Layout);
				jPanel2.setBounds(0, 0, 730, 62);
				{
					jnombre = new JLabel();
					jPanel2.add(jnombre, BorderLayout.NORTH);
					jnombre.setBounds(17, 5, 701, 17);
					jnombre.setHorizontalTextPosition(SwingConstants.CENTER);
					jnombre.setHorizontalAlignment(SwingConstants.CENTER);
					jnombre.setPreferredSize(new java.awt.Dimension(730, 28));
				}
				{
					pnlAux = new JPanel();
					jPanel2.add(pnlAux, BorderLayout.CENTER);
					{
						cargarTabla = new JButton();
						pnlAux.add(cargarTabla);
						cargarTabla.setText("Buscar Clientes Morosos");
						cargarTabla.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
								refresh();
							}
						});
					}
				}
			}

			{
				Clientes = new JPanel();
				BorderLayout ClientesLayout = new BorderLayout();
				Clientes.setLayout(ClientesLayout);
				getContentPane().add(Clientes, BorderLayout.CENTER);
				Clientes.setBounds(0, 62, 730, 100);
				{
					jScrollPane = new JScrollPane();
					Clientes.add(jScrollPane, BorderLayout.CENTER);
					jScrollPane.setBounds(0, 0, 730, 100);
					jScrollPane.setPreferredSize(new java.awt.Dimension(730,
							131));
					{
						TableModel tablaModel = new DefaultTableModel(
								new String[][] { {}, {} }, new String[] {});
						tabla = new JTable();
						jScrollPane.setViewportView(tabla);
						tabla.setAutoCreateRowSorter(true);// coso para
															// reordenar
						tabla.setModel(tablaModel);
						tabla.addMouseListener(new MouseAdapter() {
							@Override
							public void mouseReleased(MouseEvent arg0) {
								int row = tabla.rowAtPoint(arg0.getPoint());
								Long value = (Long) tabla.getValueAt(row, 5);

								if (value != null)
									verificarCuotas(value.intValue());

							}
						});
					}

				}
			}
			{
				jPanel3 = new JPanel();
				BorderLayout jPanel3Layout = new BorderLayout();
				getContentPane().add(jPanel3, BorderLayout.SOUTH);
				jPanel3.setLayout(jPanel3Layout);
				jPanel3.setBounds(0, 162, 730, 282);
				jPanel3.setPreferredSize(new java.awt.Dimension(730, 280));
				{
					cartel = new JPanel();
					BorderLayout cartelLayout = new BorderLayout();
					cartel.setLayout(cartelLayout);
					jPanel3.add(cartel, BorderLayout.NORTH);
					cartel.setPreferredSize(new java.awt.Dimension(730, 47));
					{
						infoP = new JLabel();
						cartel.add(infoP);
						infoP.setText("Detalles: Cuotas Impagas.");
						infoP.setBounds(12, 7, 706, 15);
						infoP.setHorizontalAlignment(SwingConstants.CENTER);
						infoP.setHorizontalTextPosition(SwingConstants.CENTER);
						infoP.setPreferredSize(new java.awt.Dimension(730, 26));
					}
				}
				{
					tablaImpagos = new JPanel();
					BoxLayout jPanel1Layout = new BoxLayout(tablaImpagos,
							javax.swing.BoxLayout.X_AXIS);
					tablaImpagos.setLayout(jPanel1Layout);
					jPanel3.add(tablaImpagos, BorderLayout.CENTER);
					{
						jScrollPane1 = new JScrollPane();
						tablaImpagos.add(jScrollPane1);
						jScrollPane1.setBounds(-2, 28, 730, 150);
						jScrollPane1.setPreferredSize(new java.awt.Dimension(
								730, 111));
						{
							TableModel jTable1Model = new DefaultTableModel(
									new String[][] { {}, {} }, new String[] {});
							cuotasImpagas = new JTable();
							jScrollPane1.setViewportView(cuotasImpagas);
							cuotasImpagas.setModel(jTable1Model);
							cuotasImpagas.setAutoCreateRowSorter(true);
						}
					}
				}
				{
					informacion = new JPanel();
					jPanel3.add(informacion, BorderLayout.SOUTH);
					informacion.setLayout(null);
					informacion
							.setPreferredSize(new java.awt.Dimension(730, 99));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void refresh() {
		jnombre.setText("Empleado: " + serv.getEmpleado() + ". Legajo: "
				+ serv.getLegajo() + ".");
		java.util.Date fecha = new Date();
		java.sql.Date r = java.sql.Date.valueOf((new SimpleDateFormat(
				"yyyy-MM-dd")).format(fecha));
		Resultado resultado = serv
				.realizarConsulta("SELECT * FROM (SELECT nro_cliente, tipo_doc, nro_doc, nombre, apellido, nro_prestamo, monto, cant_meses, valor_cuota, count(*) as cant_atrasadas FROM Cliente NATURAL JOIN Prestamo NATURAL JOIN Pago WHERE fecha_pago IS NULL and fecha_venc < '"
						+ r
						+ "' GROUP BY nro_prestamo) A WHERE cant_atrasadas > 1");

		if (resultado.fueExitoso()) {
			rellenarTabla(this.tabla, resultado);
		} else {
			JOptionPane.showMessageDialog(
					SwingUtilities.getWindowAncestor(this),
					resultado.getExcepcion() + "\n",
					"Error al ejecutar la consulta. \n",
					JOptionPane.ERROR_MESSAGE);
		}
	}

	private void verificarCuotas(int prestamo) {
		this.prestamo = prestamo;
		infoP.setText("Detalles: Cuotas Impagas. Prestamo #" + prestamo);

		Resultado r = serv
				.realizarConsulta("SELECT nro_pago, valor_cuota, fecha_venc FROM Prestamo NATURAL JOIN Pago WHERE nro_prestamo = '"
						+ prestamo + "' and fecha_pago is NULL");

		if (r.fueExitoso()) {
			rellenarTabla(this.cuotasImpagas, r);
		} else {
			JOptionPane.showMessageDialog(
					SwingUtilities.getWindowAncestor(this), r.getExcepcion()
							+ "\n", "Error al ejecutar la consulta. \n",
					JOptionPane.ERROR_MESSAGE);
		}
	}

	private void rellenarTabla(JTable tabla, Resultado r) {
		ConsultasTableModel modelo = new ConsultasTableModel();

		String[] columnas = r.getColumnas();
		String[] tipo = r.getTipos();
		try {
			for (int i = 0; i < columnas.length; i++) {
				String columnaNombre = columnas[i];
				Class columnaTipo = Class.forName(tipo[i]);
				boolean columnaEditable = false;
				modelo.agregarColumna(columnaNombre, columnaTipo,
						columnaEditable);
			}

			tabla.setModel(modelo);

			Vector<Object[]> filas = r.getFilas();
			for (Object[] f : filas)
				if (f != null)
					((ConsultasTableModel) tabla.getModel()).addRow(f);
		} catch (ClassNotFoundException e) {

		}
	}
}
